﻿using K3Cloud.WebApi.Core.IoC;
using K3Cloud.WebApi.Core.IoC.DataEntity;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

// 生成实体类
namespace FormEntityCreation
{
    internal class Program
    {
        private static void Main()
        {
            //var serviceProvider = new ServiceCollection()
            //    .AddStackExchangeRedisCache(options =>
            //    {
            //        options.Configuration = "localhost,abortConnect=false,defaultDatabase=2";
            //        options.InstanceName = "FEC_";
            //    })
            //   .AddSingleton<ICacheService, MyRedisCache>()
            //   .BuildServiceProvider();
            //var cacheService = serviceProvider.GetService<ICacheService>();
            //K3Services.AddK3Sugar(cacheService);
            K3Services.AddK3Sugar();
            //Task.Run(async () =>
            //{
            //    var obj = await K3CloudApiSdk.Builder().QueryBusinessInfo(new { FormId = "BD_STOCK" });
            //    Console.WriteLine(obj);
            //});
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("请输入表单ID（FormId）:如：BD_STOCK");
            string FormID = Console.ReadLine();
            Console.ForegroundColor = ConsoleColor.White;
            if (string.IsNullOrEmpty(FormID)) { FormID = "BD_STOCK"; }
            int LanguageId1 = 2052;
            int LanguageId2 = 1033;
            // 读取path文件
            //string path = @"tmp.json";
            //string json = File.ReadAllText(path);

            // 将json字符串序列化为K3BusinessInfoResult对象
            //var k3BusinessInfoResult = JsonConvert.DeserializeObject<K3ApiResult<K3BusinessInfoResult>>(json);
            K3ApiResult<K3BusinessInfoResult> k3BusinessInfoResult = K3Scoped.Client.QueryBusinessInfoAsync(FormID).GetAwaiter().GetResult();
            if (k3BusinessInfoResult != null)
            {
                if (!k3BusinessInfoResult.Result.ResponseStatus.IsSuccess)
                {
                    Console.WriteLine(k3BusinessInfoResult.Result.ResponseStatus.Errors.FirstOrDefault()?.Message);
                    return;
                }
            }
            string jsonStr = JsonConvert.SerializeObject(k3BusinessInfoResult);
            // 将jsonStr写入tmp.json文件
            File.WriteAllText(FormID + ".json", jsonStr);

            // 查找k3BusinessInfoResult对象中的NeedReturnData属性
            K3BusinessNeedReturn needReturnData = k3BusinessInfoResult.Result.NeedReturnData;
            // 生成实体类，类名是needreturndata的id
            StringBuilder sb = new();
            // 获取AssemblyTitle属性值
            AssemblyTitleAttribute assemblyTitle = Assembly.GetCallingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false)[0] as AssemblyTitleAttribute;

            // 获取当前空间的命名空间
            _ = sb.Append("using System;\r\n");
            _ = sb.Append("using System.Collections.Generic;\r\n");
            _ = sb.Append("using System.Linq;\r\n");
            _ = sb.Append("using System.Text;\r\n");
            _ = sb.Append("using System.Threading.Tasks;\r\n");
            _ = sb.Append("\r\n");
            _ = sb.Append("namespace " + assemblyTitle.Title + ".DataEntity\r\n");
            _ = sb.Append("{\r\n");
            // 注释为needreturndata的name的LanguageId语言的值
            string FormName = string.Empty;
            K3LanguageTranslate kl = needReturnData.Name.Find(x => x.Lcid == LanguageId1);
            FormName = kl != null ? kl.Value : needReturnData.Name.Find(x => x.Lcid == LanguageId2).Value;
            _ = sb.Append("\t/// <summary>\r\n");
            _ = sb.Append("\t/// " + FormName + "\r\n");
            _ = sb.Append("\t/// </summary>\r\n");
            _ = sb.Append("\tpublic class " + needReturnData.Id + "\r\n");
            _ = sb.Append("\t{\r\n");
            // 获取needreturndata的PkFieldName属性值
            string pkFieldName = needReturnData.PkFieldName;
            // 获取needreturndata的PkFieldType属性值
            Type pkFieldType = needReturnData.PkFieldType;
            // 注释为needreturndata的PkFieldName属性值
            _ = sb.Append("\t\t/// <summary>\r\n");
            _ = sb.Append("\t\t/// " + pkFieldName + "\r\n");
            _ = sb.Append("\t\t/// </summary>\r\n");
            _ = sb.Append("\t\tpublic " + pkFieldType + " " + pkFieldName + " { get; set; }\r\n");

            // 获取needreturndata的entrys属性值
            System.Collections.Generic.List<K3Table> entrys = needReturnData.Entrys;
            // 遍历entrys
            foreach (K3Table entry in entrys)
            {
                // 获取entry的Name的LanguageId语言值
                string entryName = string.Empty;
                K3LanguageTranslate ekl = entry.Name.Find(x => x.Lcid == LanguageId1);
                entryName = ekl != null ? ekl.Value : entry.Name.Find(x => x.Lcid == LanguageId2).Value;
                // 注释为entry的Name的LanguageId语言值
                _ = sb.Append("\t\t#region " + entryName + "\r\n");
                // 获取entry的Key属性值
                string entryKey = entry.Key;
                // 获取entry的EntryPkFieldName属性值
                string entryPkFieldName = entry.EntryPkFieldName;
                // 获取entry的PkFieldType属性值
                Type entryPkFieldType = entry.PkFieldType;

                // 获取entry的SeqFieldKey属性值
                string seqFieldKey = entry.SeqFieldKey;
                if (!string.IsNullOrEmpty(seqFieldKey))
                {
                    // 注释为entry的PkFieldName属性值
                    _ = sb.Append("\t\t/// <summary>\r\n");
                    _ = sb.Append("\t\t/// " + entryName + "主键" + entryPkFieldName + "\r\n");
                    _ = sb.Append("\t\t/// </summary>\r\n");
                    _ = sb.Append("\t\tpublic " + entryPkFieldType + " " + entryKey + "_" + entryPkFieldName + " { get; set; }\r\n");
                    // 注释为entry的SeqFieldKey属性值
                    _ = sb.Append("\t\t/// <summary>\r\n");
                    _ = sb.Append("\t\t/// " + entryName + "序列\r\n");
                    _ = sb.Append("\t\t/// </summary>\r\n");
                    _ = sb.Append("\t\tpublic int " + entryKey + "_" + seqFieldKey + " { get; set; }\r\n");
                }
                // 获取entry的Fields属性值
                System.Collections.Generic.List<K3FieldResult> fields = entry.Fields;
                // 遍历fields
                foreach (K3FieldResult field in fields)
                {
                    // 获取field的Name的LanguageId语言值
                    string fieldName = string.Empty;
                    K3LanguageTranslate klv = field.Name.Find(x => x.Lcid == LanguageId1);
                    fieldName = klv != null ? klv.Value : field.Name.Find(x => x.Lcid == LanguageId2).Value;
                    // 注释为field的Name的LanguageId语言值
                    _ = sb.Append("\t\t/// <summary>\r\n");
                    _ = sb.Append("\t\t/// " + fieldName + "\r\n");
                    _ = sb.Append("\t\t/// </summary>\r\n");
                    // 获取field的key属性值
                    string key = field.Key;
                    // 获取field的ElementType属性值
                    int elementType = field.ElementType;
                    // 获取field的FieldType属性值
                    SqlStorageType fieldType = field.FieldType;
                    // 获取field的MustInput属性值
                    int mustInput = field.MustInput;
                    string mustInputStr = mustInput == 1 ? "" : "?";
                    if (fieldType == SqlStorageType.Sqlchar)
                    {
                        Debug.WriteLine(key);
                    }
                    _ = sb.Append("\t\tpublic " + K3BusinessToCSharpType.GetType(fieldType) + mustInputStr + " " + key + " { get; set; }\r\n");
                    // 获取field的LookUpObjectFormId属性值
                    string lookUpObjectFormId = field.LookUpObjectFormId;
                    if (!string.IsNullOrEmpty(lookUpObjectFormId))
                    {
                        K3ApiResult<K3BusinessInfoResult> subBusinessInfo = K3Scoped.Client.GetBusinessInfoAsync(lookUpObjectFormId).GetAwaiter().GetResult();
                        System.Collections.Generic.List<K3FieldResult> subFields = subBusinessInfo.Result.NeedReturnData.Entrys
                            .Where(t => t.Fields.Any(x => x.Key is "FNumber" or "FName" or "FShortName" or "FDataValue"))
                            .Select(t => t.Fields).FirstOrDefault();
                        if (subFields == null) { continue; }
                        int subFieldsCount = 0;
                        for (int i = 0; i < subFields.Count; i++)
                        {
                            if (subFieldsCount >= 3) { break; }
                            if (subFields[i].Key.Equals("FNumber") || subFields[i].Key.Equals("FName") || subFields[i].Key.Equals("FShortName") || subFields[i].Key.Equals("FDataValue"))
                            {
                                string summaryTitle = string.Empty;
                                K3LanguageTranslate slv = subFields[i].Name.Find(t => t.Lcid == LanguageId1);
                                summaryTitle = slv != null ? slv.Value : subFields[i].Name.Find(x => x.Lcid == LanguageId2).Value;
                                _ = sb.Append("\t\t/// <summary>\r\n");
                                _ = sb.Append("\t\t/// " + fieldName + summaryTitle + "\r\n");
                                _ = sb.Append("\t\t/// </summary>\r\n");
                                _ = sb.Append("\t\tpublic string " + key + "__" + subFields[i].Key + " { get; set; }\r\n");
                                subFieldsCount++;
                            }
                        }
                    }
                }
                _ = sb.Append("\t\t#endregion" + "\r\n");
            }
            _ = sb.Append("\t}\r\n}");

            Console.WriteLine(sb.ToString());
            // 将生成的实体类写入到文件中
            File.WriteAllText("../../../DataEntity/" + needReturnData.Id + ".cs", sb.ToString());
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("...按任意键结束...");
            _ = Console.ReadKey();
        }
    }
}
